<?php

namespace App\Http\Controllers\Frontend\V10\Repay;

use App\Jobs\RepayCommonJobQueue;
use App\Models\RepayRecord;
use App\Models\RepayRecordCommon;
use App\Models\RepaySummary;
use App\Models\UserBankCard;
use App\Http\Controllers\Controller;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class OldRepayController extends Controller
{

    protected $user;
    public function __construct()
    {
        $this->middleware('auth:api');
        $this->user = auth('api')->user();
    }

    public function setMoneyRepay($data){
        //参数判断
        if( !isset( $data['card_id'] ) || !isset( $data['repay_type'] ) ){
            $returnData['flag'] = false;
            $returnData['msg'] = '请选择正确银行卡或还款方式';
            return $returnData;
        }
        $is_use_card = UserBankCard::select('id')->where('id',$data['card_id'])->where('uid',$this->user->id)->first();
        if(!$is_use_card){
            $returnData['flag'] = false;
            $returnData['msg'] = '请选择正确银行卡';
            return $returnData;
        }
        // 1 还当期 2 全部还清
        if($data['repay_type'] == 1){

            $res = $this->repayCurrent($data['card_id']);
        }elseif($data['repay_type'] == 2){

            $res = $this->repayAll($data['card_id']);
        }else{
            $returnData['flag'] = false;
            $returnData['msg'] = '请选择类型';
            return $returnData;
        }

        return $res;
    }


    /**
     * Description:当期还
     * Author:lijiafei
     * @return
     */
    protected function repayCurrent($bank_cards_id){
        //获取当前应该还哪期的数据
        $repayInfo = RepaySummary::getRepaySummaryLog($this->user->id);
        $result = $this->validateCurrentRepay($repayInfo);
        if(!$result['flag']){
            return $result;
        }

        //判断当前银行卡是否有效
        $hold_agreement_num = UserBankCard::getHoldAgreementNumById($bank_cards_id,$repayInfo->id);
        if(!$hold_agreement_num){
            $returnData['flag'] = false;
            $returnData['msg'] = '请选择有效的银行卡';
            return $returnData;
        }
        //保存当前银行卡以及以后的所有银行卡信息
        $isSave = RepaySummary::saveBankInfo($bank_cards_id);
        if($isSave === false){
            $returnData['flag'] = false;
            $returnData['msg'] = '还款失败,请稍后重试';
            return $returnData;
        }

        $common_status = $repayInfo->recordOne->common->status;
        if($common_status == RepayRecordCommon::STATUS_TWO){
            $returnData['flag'] = false;
            $returnData['msg'] = '正在还款中';
            return $returnData;
        }

        //判断是否达到当日最大次数
        $isCheck = $this->checkApiNumber($repayInfo->recordOne->summary_id,$repayInfo->recordOne->uid);
        if(isset($isCheck['flag']) && $isCheck['flag'] == false){
            return $isCheck;
        }
        $res = RepaySummary::setCurrentRepayJob($repayInfo->recordOne,RepayRecord::REPAY_TYPE_MANUAL);
        return $res;
    }


    protected function repayAll($bank_cards_id){
        //获取当前应该还哪期
        $repayInfo = RepaySummary::getRepaySummaryLog($this->user->id);
        $result = $this->validateAllRepay($repayInfo);
        if(!$result['flag']){
            return $result;
        }

        //判断当前银行卡是否有效
        $hold_agreement_num = UserBankCard::getHoldAgreementNumById($bank_cards_id,$repayInfo->id);
        if(!$hold_agreement_num){
            $returnData['flag'] = false;
            $returnData['msg'] = '请选择有效的银行卡';
            return $returnData;
        }

        //获取全部还清的时候的记录 period = 0的记录
        $info = RepaySummary::getAllRepayLog($repayInfo->id,$this->user->id);
        if(!$info){
            $returnData['flag'] = false;
            $returnData['msg'] = '提前结清失败';
            return $returnData;
        }

        $isSave = RepaySummary::saveBankInfo($bank_cards_id);
        if($isSave === false){
            $returnData['flag'] = false;
            $returnData['msg'] = '还款失败,请稍后重试';
            return $returnData;
        }
        //判断是否达到当日最大次数
        $isCheck = $this->checkApiNumber($info->recordOne->summary_id,$info->recordOne->uid);
        if(isset($isCheck['flag']) && $isCheck['flag'] == false){
            return $isCheck;
        }
        $res = RepaySummary::setAllRepayJob($info->recordOne,RepayRecord::REPAY_TYPE_MANUAL);
        return $res;
    }

    /**
     * Description:检查是否超过最大请求次数
     * Author:lijiafei
     * @param $summary_id int repay_summary表id
     * @param $uid int 用户id
     * @return bool
     */
    protected function checkApiNumber($summary_id,$uid)
    {
        //判断是否达到当日最大次数
        $is_send_api = RepaySummary::checkApiNumber($summary_id,$uid,RepaySummary::COMMON_API);
        if(!$is_send_api){
            $returnData['flag'] = false;
            $returnData['msg'] = '当日请求次数已达上限';
            return $returnData;
        }

        //判断是否达到当日最大次数
        $is_send_api = RepaySummary::checkApiNumber($summary_id,$uid,RepaySummary::MONEY_API);
        if(!$is_send_api){
            $returnData['flag'] = false;
            $returnData['msg'] = '当日请求次数已达上限';
            return $returnData;
        }
        return $returnData['flag'] = true;
    }

    /**
     * Description:验证还当期
     * Author:lijiafei
     * @param $repayInfo
     * @return mixed
     */
    protected function validateCurrentRepay($repayInfo){
        Log::debug('还款:农信,老光大的数据' . json_encode($repayInfo));
        if(!$repayInfo){
            $returnData['flag'] = false;
            $returnData['msg'] = '当前没有还款计划';
            return $returnData;
        }

        if($repayInfo->recordOne->status == RepayRecord::STATUS_TWO){
            //代表这条记录还在轮询中,不要还款
            $returnData['flag'] = false;
            $returnData['msg'] = '正在还款中,不能发起新的还款';
            return $returnData;
        }

        $isCurrentRepay = RepaySummary::isCurrentRepay($repayInfo->id);
        if(!$isCurrentRepay){
            $returnData['flag'] = false;
            $returnData['msg'] = '当前不能进行逐期还款';
            return $returnData;
        }

        //借款当日不能提前还款
        $createDate = Carbon::parse(Carbon::parse($repayInfo->created_at)->toDateString());
        $today = Carbon::today();
        if($createDate->eq($today)){
            $returnData['flag'] = false;
            $returnData['msg'] = '放款当日不能提前还款';
            return $returnData;
        }
        $returnData['flag'] = true;
        $returnData['msg'] = '';
        return $returnData;
    }

    /**
     * 验证全部还清
     */
    protected function validateAllRepay($repayInfo){
        Log::debug('还款:农信,老光大的全部结清数据' . json_encode($repayInfo));
        if($repayInfo === false){
            $returnData['flag'] = false;
            $returnData['msg'] = '不能进行正常还款';
            return $returnData;
        }
        if($repayInfo->period  === $repayInfo->period_count){
            $returnData['flag'] = false;
            $returnData['msg'] = '最后一期不能进行提前结清';
            return $returnData;
        }
        if($repayInfo->period  === 1){
            $returnData['flag'] = false;
            $returnData['msg'] = '第一期不能进行提前结清';
            return $returnData;
        }
        if($repayInfo->recordOne->status == RepayRecord::STATUS_TWO){
            //代表这条记录还在轮询中,不要还款
            $returnData['flag'] = false;
            $returnData['msg'] = '正在还款中,不能发起新的还款';
            return $returnData;
        }
        $day = count_days(Carbon::now()->toDateString(),$repayInfo->recordOne->normal_date);
        if($day > 0){
            $returnData['flag'] = false;
            $returnData['msg'] = '逾期不能进行提前结清';
            return $returnData;
        }
        //判断是否可以全部还清
        $isAllRepay = RepaySummary::isAllRepay($repayInfo->recordOne);
        if(!$isAllRepay){
            $returnData['flag'] = false;
            $returnData['msg'] = '当前状态不能进行提前结清';
            return $returnData;
        }

        $returnData['flag'] = true;
        $returnData['msg'] = '';
        return $returnData;
    }
}
